<?php

namespace app\service;

use app\ErrorCode;
use app\exception\ApiException;
use app\traits\Singleton;
use Exception;
use Firebase\JWT\BeforeValidException;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Firebase\JWT\SignatureInvalidException;

class JwtService
{
    use Singleton;
    protected static $key = '!@#$%*&'; // Replace with your own secret key
    protected static $alg = 'HS256';

    public function encode($data, $expiration = 3600)
    {
        $payload = [
            'iss' => 'your_issuer',  // Issuer
            'aud' => 'your_audience', // Audience
            'iat' => time(),        // Issued at
            'exp' => time() + $expiration, // Expiration time
            'data' => $data         // Custom data
        ];
        return JWT::encode($payload, self::$key, self::$alg);
    }

    public function decode($token)
    {
        try {
            JWT::$leeway = 60;//当前时间减去60，把时间留点余地
            $decoded = JWT::decode($token, new Key(self::$key, self::$alg));
            return $decoded->data;
        } catch (SignatureInvalidException $exception) {
            throw new ApiException("签名错误",ErrorCode::UNAUTHORIZED);
        } catch (BeforeValidException $exception) {
            throw new ApiException("token还未到允许使用的时间",ErrorCode::UNAUTHORIZED);
        } catch (ExpiredException $exception) {
            throw new ApiException("token 已过期",ErrorCode::UNAUTHORIZED);
        }  catch (Exception $e) {
            throw new ApiException("非法请求:" . $e->getMessage(),ErrorCode::INVALID_PARAMS);
        }
    }
}